<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false"
             :close-on-press-escape="false" width="800">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
             label-width="120px">
      <el-form-item label="客户" prop="customId">
        <el-select v-model="dataForm.customId" placeholder="客户" style="width: 240px">
          <el-option
            v-for="item in customerOpt"
            :key="item.cusId"
            :label="item.cusName"
            :value="item.cusId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="foodStatus">
        <el-select v-model="dataForm.foodStatus" placeholder="类型 0-手动 1-自动" style="width: 240px">
          <el-option
            v-for="item in [{value: 1,label: '手动',},{value: 0,label: '自动',}]"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="方案日期" prop="planDate">
        <el-date-picker
          v-model="dataForm.planDate"
          type="datetime"
          placeholder="Pick a day"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="时段" prop="planDayTime">
        <el-select v-model="dataForm.planDayTime" placeholder="1-早 2-中 3-晚" style="width: 240px">
          <el-option
            v-for="item in planDayTimeOpt"
            :key="item.key"
            :label="item.value"
            :value="item.key"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="起始BMI" prop="startBmi">
        <el-input type="number" v-model="dataForm.startBmi" placeholder="起始BMI" style="width: 400px"></el-input>
      </el-form-item>
      <el-form-item label="结束BMI" prop="endBmi">
        <el-input type="number" v-model="dataForm.endBmi" placeholder="结束BMI" style="width: 400px"></el-input>
      </el-form-item>

      <el-divider/>

    </el-form>

    <div>
      <h3>添加食物</h3>
      <el-form :model="planFood" ref="foodsRef" :rules="planRules" style="margin-left: 0" label-width="120px">
        <el-form-item label="食物名称" prop="foodId">
          <el-select v-model="planFood.foodId" placeholder="食物名称" style="width: 240px">
            <el-option
              v-for="item in foodOpt"
              :key="item.id"
              :label="item.foodName"
              :value="item.id"
            />
          </el-select>
          <span style="color: red;margin-left: 20px;" v-show="foodSelectText.weight">重量：{{foodSelectText.weight}}，热量：{{foodSelectText.trophy}}</span>
        </el-form-item>
        <el-form-item label="食物重量(克)" prop="foodWeight">
          <el-input type="number" v-model="planFood.foodWeight" placeholder="食物重量(克)" style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="热量(大卡)" prop="trophy">
          <el-input type="number" v-model="planFood.trophy" placeholder="热量(大卡)" style="width: 400px"></el-input>
          <el-button type="primary" @click="addFoods" style="margin-left: 20px;">添加</el-button>
        </el-form-item>
      </el-form>

      <el-table v-if="dataForm.foodPlanDetails.length > 0" :data="dataForm.foodPlanDetails" stripe style="width: 100%">
        <el-table-column prop="foodName" label="食物名称" width="180"/>
        <el-table-column prop="foodWeight" label="食物重量(克)" width="180"/>
        <el-table-column prop="trophy" label="热量(大卡)"/>
      </el-table>
    </div>
    <el-divider/>
    <template #footer>
      <div style="width: 350px">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref, watch,watchEffect} from "vue";
import baseService from "@/service/baseService";
import {ElMessage} from "element-plus";
import {type PlanFood} from '@/types/health'

const props = defineProps(['foodOption'])
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const foodsRef = ref();
const foodSelectText = ref({weight:'',trophy:''});
const planFood = ref({});
const foodOpt = ref<Array<object>>([{}]);
const customerOpt = ref<Array<object>>([{}]);
const isUpdate = ref(false);

const dataForm = reactive({
  id: '',
  foodStatus: 1,
  planDate: '',
  planDayTime: '',
  customId: '',
  createDate: '',
  creator: '',
  updateDate: '',
  updater: '',
  startBmi: '',
  endBmi: '',
  foodPlanDetails: [{}]
});

const rules = ref({
  foodStatus: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  planDate: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  planDayTime: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  customId: [
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  startBmi: [
    {required: true, message: '必填项不能为空', trigger: 'blur'},
    {min: 0, message: 'bmi必须大于0', trigger: 'blur'},
  ],
  endBmi: [
    {required: true, message: '必填项不能为空', trigger: 'blur'},
    {min: 0, message: 'bmi必须大于0', trigger: 'blur'}
  ],
});
const planRules = ref({
  foodId:[
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  startBmi:[
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
  endBmi:[
    {required: true, message: '必填项不能为空', trigger: 'blur'}
  ],
})
const planDayTimeOpt = ref([{key: 1, value: '早'}, {key: 2, value: '中'}, {key: 3, value: '晚'}])

const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";
  isUpdate.value = false
  dataForm.foodPlanDetails.length = 0
  foodSelectText.value = {weight:'',trophy:''};
  if (dataFormRef.value)foodsRef.value.resetFields()
  // 请求食物列表
  baseService.get("/health/food/page?order=&orderField=&page=1&limit=10000").then((res) => {
    foodOpt.value = res.data.list
  })
  // 请求客户列表
  baseService.get("/health/hmcustomer/page?order=&orderField=&page=1&limit=10000").then((res) => {
    customerOpt.value = res.data.list
  })
  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (id) {
    isUpdate.value = true
    getInfo(id);
  }
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get("/health/foodplan/" + id).then((res) => {
    Object.assign(dataForm, res.data);
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.id ? baseService.post : baseService.put)("/health/foodplan", dataForm).then((res) => {
      ElMessage.success({
        message: '成功',
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

const addFoods = () => {
  foodsRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    let food = foodOpt.value?.find(f => f.id == planFood.value.foodId);
    if (food) planFood.value.foodName = food.foodName
    dataForm.foodPlanDetails.push(JSON.parse(JSON.stringify(planFood.value)))
    planFood.value ={}
  });
}

watchEffect(() => {
  let food = foodOpt.value.find(food => planFood.value.foodId == food.id);
  if (food) {
    foodSelectText.value.weight = food.weight
    foodSelectText.value.trophy = food.foodTrophy
  }

})

defineExpose({
  init
});

</script>
